﻿;(function ($) {

$.fn.cartVM = function (options) {

	var settings = {};
	var vm = null;

	this.init = function() {
		settings = $.extend({} , $.fn.cartVM.defaultOptions, options);
		vm = new CartViewModel();
		ko.applyBindings(vm);
		SetupCart();
		return this;
	};

	function CartViewModel() {
		var self = this;

		self.id = ko.observable();
		self.allowPartialDelivery = ko.observable(false);
		self.pageHref = ko.observable(settings.cartPageUrl);
		self.visitorId = ko.observable(settings.visitorId);
		self.authenticationTicket = ko.observable(settings.authenticationTicket);

		self.items = ko.observableArray([]);
		self.grandTotal = ko.computed(function() {
			var total = 0;
			$.each(self.items(), function() { total += this.grandTotal() });
			return total;
		});
		self.grandTaxTotal = ko.computed(function() {
			var total = 0;
			$.each(self.items(), function() { total += this.grandTaxTotal() });
			return total;
		});
		self.grandTotalWithTax = ko.computed(function() {
			var total = self.grandTotal() + self.grandTaxTotal();
			return total;
		});

		// Methods
		self.addItem = function(item) {
			self.items.push(item);
		}.bind(self);

		self.removeItem = function(item) {
			var index = self.items.indexOf(item);
			var result = RemoveItem(index);
			if (result) {
				self.items.splice(index, 1);
			}
		}
	}

	function Item(index, data) {
		var self = this;

		self.parent = null;
		self.index = ko.computed(function() {
			var index = vm.items.indexOf(self);
			return index;
		});
		self.quantity = ko.observable(data.Quantity);
		self.price = ko.observable(data.SalePrice.Value);
		self.taxRate = ko.observable(data.SalePrice.TaxRate);
		self.stockInfo = new StockInfo(data.ProductStockInfo);
		self.product = new Product(data.Product);

		self.total = ko.computed(function() {
			var total = (self.price() * self.quantity()) / (self.product.saleUnitValue() * 1.0);
			return total;
		});
		self.totalTax = ko.computed(function() {
			var total = (self.price() * self.quantity() * self.taxRate()) / (self.product.saleUnitValue() * 1.0);
			return total;
		});
		self.totalWithTax = ko.computed(function() {
			var total = self.total() + self.totalTax();
			return total;
		});

		self.grandTotal = ko.computed(function() {
			var total = self.total();
			return total;
		});
		self.grandTaxTotal = ko.computed(function() {
			var total = self.totalTax();
			return total;
		});
		self.grandTotalWithTax = ko.computed(function() {
			var total = self.grandTotal() + self.grandTaxTotal();
			return total;
		});

		self.addQuantity = function() {
			var quantity = self.quantity() + self.product.packaging();
			var result = ChangeQuantity(vm.id, self.index(), quantity);
			if (result)
			{
				self.quantity(quantity);
			}
		}
		self.removeQuantity = function() {
			var quantity = self.quantity() - self.product.packaging();
			quantity = Math.max(self.product.packaging(), quantity);
			if (quantity == self.quantity())
			{
				return;
			}
			var result = ChangeQuantity(vm.id, self.index(), quantity);
			if (result)
			{
				self.quantity(quantity);
			}
		}
	}


	/*
	
	Helpers

	*/

	function SetupCart() {

		url = '/api/cart/getcurrentcart/' + settings.visitorId;

		$.ajax({
			type : 'GET',
			contentType : 'application/json',
			url : url,
			data : { authenticationTicket : settings.authenticationTicket },
			success : function (data) {
				if (data == null) {
					return;
				}
				vm.id(data.Code);
				for(var i = 0; i < data.Items.length; i++) {
					var dataItem = data.Items[i];
					var item = new Item(i, dataItem);
					vm.addItem(item);
				};
			}
		});
	}

	function RemoveItem(index) {
		var result = false;
		$.ajax({
			type : 'DELETE',
			url : '/api/cart/deleteitem',
			data : {
				id : vm.id,
				index : index
			},
			async : false,
			success : function(data) {
				result = true;
			}
		});
		return result;
	}

	function ChangeQuantity(cartId, index, quantity) {
		var result = false;
		$.ajax({
			type : 'GET',
			contentType : 'application/json',
			url : '/api/cart/changeitemquantity',
			data : {
				id : cartId,
				index : index,
				quantity : quantity
			},
			async : false,
			success : function(data) {
				result = true;
			}
		});
		return result;
	}

	return this.init();
};

$.fn.cartVM.defaultOptions = {
	cartPageUrl : null,
	visitorId : null,
	authenticationTicket : null
};

})(jQuery);

